<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2019/6/5
 * Time: 17:07
 */

namespace Hilaoyu\Utils\Drivers\Sms;


use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\Utils\UtilArr;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilRegex;
use Hilaoyu\Utils\UtilStr;
use Yunpian\Sdk\YunpianClient;

class Yunpian
{
    use ErrorsTrait;
    protected $config = [];

    public function __construct($config=[])
    {

        $this->setConfig($config);
    }

    public function setConfig($config=[]){
        $this->config = (array)$config;
    }

    public function getConfig($key=''){
        $key = trim($key);

        if($key){
            return UtilArr::get($this->config,$key);
        }

        return $this->config;
    }

    protected function buildTplValue($content,$tpl=''){

        if(empty($tpl)){
            return UtilArr::toString($content);
        }

        $content = UtilStr::replace($tpl,(array)$content);

        return $content;
    }

    public function send($phone,  $content,$tpl = '') {
        $phone = trim($phone);
        $tpl = trim($tpl);

        if(!UtilRegex::isMobile($phone)){
            $this->setError('手机号格式错误');
            return false;
        }

        $sms = YunpianClient::create($this->getConfig('app_key'));
        $param = [
            YunpianClient::MOBILE => $phone,
            YunpianClient::TEXT   => $this->buildTplValue($content,$tpl),
        ];

        $res = $sms->sms()->single_send($param);


        if ($res && $res->isSucc()) {
            return TRUE;
        } else {
            //dd($res);
            $this->setError($res->code() .":".$res->msg() );
            return FALSE;
        }
    }
}
